﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WhittleList.Bll
{
    public partial class Item : IValidate, IConcurrent
    {
        partial void OnValidate(System.Data.Linq.ChangeAction action)
        {
            if (!IsValid)
                throw new Exceptions.ValidationException("Rule Violation prevented saving", GetRuleViolations());
        }

        #region IValidate Members

        public bool IsValid
        {
            get { return GetRuleViolations().Count() == 0; }
        }

        public virtual IEnumerable<RuleViolation> GetRuleViolations()
        {
            if (string.IsNullOrEmpty(Name))
                yield return new RuleViolation("Name", "Name is required");

            if (SectionId <= 0)
                yield return new RuleViolation("SectionId", "SectionId is required");
        }

        #endregion

        internal void OnInserting(User currentUser)
        {
            this._LastUpdatedById = this._CreatedById = currentUser.Id;
            this._UTCLastUpdated = this._UTCCreated = DateTime.UtcNow;
        }

        internal void OnUpdating(User currentUser)
        {
            this._LastUpdatedById = currentUser.Id;
            this._UTCLastUpdated = DateTime.UtcNow;
        }

        public bool CheckConcurrent(System.Data.Linq.Binary cid)
        {
            return this.CID == cid;
        }

        public void EnsureConcurrent(System.Data.Linq.Binary cid)
        {
            if(!CheckConcurrent(cid))
                throw new Exceptions.ConcurrencyException();
        }
    }
}
